package com.uvnos4j.matilda.security.service;

import cn.hutool.core.util.StrUtil;
import com.uvnos4j.matilda.security.domain.AuthUser;
import com.uvnos4j.matilda.security.mapper.AuthMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 安全用户服务实现
 * <p>
 * Description:安全用户服务实现
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @see com.uvnos4j.matilda.security.service
 * @since 2020-08-31 23:31:02
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private AuthMapper authMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (StrUtil.isBlank(s)) {
            throw new UsernameNotFoundException("username is blank.");
        }

        // 用户查询
        AuthUser user = authMapper.getByUsername(s);

        if (user == null) {
            throw new UsernameNotFoundException("username not found. username:" + s);
        }

        List<GrantedAuthority> authorities = new ArrayList<>();

        // 获取用户的角色权限
        List<String> roles = authMapper.findRolesByUserId(user.getUserId());
        roles.forEach(role -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_" + role);
            authorities.add(grantedAuthority);
        });

        // 获取用户拥有的权限
        List<String> acls = authMapper.findAclsByUserId(user.getUserId());
        acls.forEach(acl -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(acl);
            authorities.add(grantedAuthority);
        });

        // 设置权限
        user.setAuthorities(authorities);
        return user;

    }

}